﻿using System;
using System.Linq;
using System.Web.Mvc;
using Safal.IncidentTracker.Domain.Abstract;
using Safal.IncidentTracker.WebUI.Models;

namespace Safal.IncidentTracker.WebUI.Controllers
{
    public class SearchController : Controller
    {
        private readonly IIncidentsRepository _incidentsRepository;
        public SearchController(IIncidentsRepository incidentsRepository )
        {
            _incidentsRepository = incidentsRepository;
        }

        public ActionResult Search(string search)
        {
            if (string.IsNullOrEmpty(search))
                return RedirectToAction("List", "Incidents", new { page = 1 });

            var incident = _incidentsRepository.Incidents
                .Where(j => j.Title.ToLower().Contains(search.ToLower()));

            var viewModel = new SearchResultsViewModel { Incidents = incident.ToList() };
            return View(viewModel);
        }

        public ActionResult AdvancedSearch(AdvancedSearch search)
        {
            if (string.IsNullOrEmpty(search.Query) &&
                string.IsNullOrEmpty(search.InjuryLocation) &&
                search.DateFrom == DateTime.MinValue &&
                search.DateTo == DateTime.MinValue 
                )
                return View("AdvancedSearch");

            search.Query = (search.Query ?? "");
            if (search.DateFrom < DateTime.Parse("1/1/1753")) search.DateFrom = DateTime.Parse("1/1/1753");
            if (search.DateTo == DateTime.MinValue) search.DateTo = DateTime.MaxValue;
            search.InjuryLocation = (search.InjuryLocation ?? "");



            var incidents = _incidentsRepository.Incidents
               .Where(j =>
                   j.Title.ToLower().Contains((search.Query).ToLower()) && 
                   (j.DateOfIncident >= search.DateFrom && j.DateOfIncident < search.DateTo ) &&
                   j.InjuryLocation.ToLower().Contains(search.InjuryLocation.ToLower()))
                   .ToList();

            var viewModel = new SearchResultsViewModel { Incidents = incidents };
            return View("Search", viewModel);

            
        }
    }
}